
package at.fhj.ase.crypto.common.util;

/**
 * Utility class providing useful string checking methods like checking for length, etc.<br>
 * There are also defined default lengths {@link #DEFAULT_STRING_LENGTH_MIN} and {@link #DEFAULT_STRING_LENGTH_MAX}
 * 
 * @author sfe | www.fh-joanneum.at | Practical Aspects of Cryptography
 */
public final class StringUtil {
  /** The default minimal string length which is <code>1</code> */
  public static final int DEFAULT_STRING_LENGTH_MIN = 1;
  /** The default maximal string length which is <code>50</code> */
  public static final int DEFAULT_STRING_LENGTH_MAX = 50;

  private StringUtil() {
    throw new AssertionError("StringUtil: Util classes are not intended/allowed to be instantiated!");
  }

  /**
   * @param stringToBeChecked the {@link String} instance we want to check
   * @return the provided {@link String} checked for <code>null</code> and a valid length of > 0.
   * @throws IllegalArgumentException if the provided {@link String} is <code>null</code> or has a length smaller 1 (empty)
   */
  public static String checkEmptyOrNull(final String stringToBeChecked) {
    if (stringToBeChecked == null || stringToBeChecked.isEmpty()) {
      throw new IllegalArgumentException("String must not be null or empty");
    }
    return stringToBeChecked;
  }

  /**
   * @return <code>stringToBeChecked</code> if it has a valid length
   */
  public static String checkLength(final String stringToBeChecked, final int minLength, final int maxLength) {
    checkEmptyOrNull(stringToBeChecked);
    if (stringToBeChecked.length() < minLength || stringToBeChecked.length() > maxLength) {
      throw new IllegalArgumentException("String must not be without length ranges (" + minLength + " - " + maxLength + " chars)");
    }
    return stringToBeChecked;
  }

  /**
   * @return <code>stringToBeChecked</code> if it has a valid length between {@link #DEFAULT_STRING_LENGTH_MIN} and {@link #DEFAULT_STRING_LENGTH_MAX}
   */
  public static String checkLengthDefaults(final String stringToBeChecked) {
    return checkLength(stringToBeChecked, StringUtil.DEFAULT_STRING_LENGTH_MIN, StringUtil.DEFAULT_STRING_LENGTH_MAX);
  }

  /** @return <code>true</code> if the provided {@link String} is valid, otherwise <code>false</code> (using {@link StringUtil#checkEmptyOrNull(String)}) */
  public static boolean isEmptyOrNull(final String stringToBeChecked) {
    try {
      StringUtil.checkEmptyOrNull(stringToBeChecked);
      return false;
    } catch (IllegalArgumentException iae) {
      return true;
    }
  }
}
